#region Imported Namespaces
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;

using BO = PHSRAG.Insight21.BusinessObjects;
using DataAccess = PHSRAG.Utility.DataAccess;
using ICachePolicy = PHSRAG.Insight21.Policy.ICachePolicy;
using SearchCriteria = PHSRAG.Insight21.SearchContext.SearchCriteria;
using PHSRAG.Insight21.InsightUtilities;
#endregion

namespace PHSRAG.Insight21.Humans
{
	/// <summary>
	/// This object holds the list of addition requests available for the logged in administrator. 
	/// The logged in user can accept or reject the request raised(Submitted).
	/// AddOns
	/// -->sorting on the addition requests.
	/// -->PDF and the Excel download.
	/// </summary>
	public class ListAdditionRequests : BO.BusinessObject
	{
		#region Constants
		private const string	AdditionRequestsKey    = "ListAdditionRequestsKey_79057FAB-8B13-4633-A81E-F39F9BEC8A2F";
		private const bool		AscendingSortSequence  = false;
		private const string	OriginalDataTableName  = "original";
		private const string	SortSequenceAscending  = "ASC";
		private const string	SortSequenceDescending = "DESC";
		#endregion

		#region Instance Variables
		private string	currentDataTableName = OriginalDataTableName;
		private bool	sortAscending = AscendingSortSequence;
		private string	sortColumn = "Date";	// Keep this in sync with the stored proc order by
		#endregion

		#region Constructor
		/// <summary>
		/// Constructs a new ListAdditionRequests object based on the prevailing cachePolicy.
		/// </summary>
		/// <param name="cachePolicy">available cachePolicy</param>
		public ListAdditionRequests(ICachePolicy cachePolicy) : base(cachePolicy)
		{
		}
		#endregion

		#region Public Properties
		/// <summary>
		/// Get the key to be used in all caching operations for this instance of the object.
		/// </summary>
		public static string CacheKey	{ get { return AdditionRequestsKey; } }

		/// <summary>
		/// Get the total number of Addition request.
		/// </summary>
		public int Count
		{
			get{return ( null == DataContainer || DataContainer.Tables[currentDataTableName] == null)? 0 :DataContainer.Tables[currentDataTableName].Rows.Count;}
		}
		
		/// <summary>
		/// Gets the sort order.
		/// </summary>
		public bool SortAscending
		{
			get { return sortAscending; }
		}

		/// <summary>
		/// Gets the name of the sort column.
		/// </summary>
		public string SortColumn
		{
			get { return sortColumn; }
		}
		#endregion

		#region caching
		/// <summary>
		/// Cache the object (ListAdditionrequest).
		/// </summary>
		public override void Cache()
		{
			CachePolicy.Cache(AdditionRequestsKey, this);
		}

		/// <summary>
		/// Remove the object(ListAdditionRequest) from the cache.
		/// </summary>
		public override void UnCache()
		{
			CachePolicy.UnCache(AdditionRequestsKey);
		}
		#endregion

		#region Public Load Methods
		/// <summary>
		/// Loads the list of addition request raised(submitted) for adding new Drug/Device.
		/// </summary>
		/// <param name="connectionString">Database connection string</param>
		/// <param name="args">Domain user ID</param>
		public override void Load(string connectionString, params object[] args)
		{
			try
			{
				DataContainer = DataAccess.GetDataSet(connectionString, "GetListAdditionRequests");
				if ( DataContainer.Tables.Count == 1 )
					DataContainer.Tables[0].TableName = OriginalDataTableName;
			}
			catch(Exception ex)
			{
				throw new Exception("Failed to load the ListAdditionRequests. Error occurred while trying to execute the Load() in ListAdditionRequests object", ex);
			}
		}
		#endregion

		#region Public Methods

		/// <summary>
		/// Get the list of Addition request objects bound by a start and end index. These indices are in the list
		/// loaded during the Load() method into the data container. Typically, the start index
		/// is on a "page" boundary, where the "page" refers to a datagrid page.
		/// Note that the total number of objects returned may be less than the requested count.
		/// </summary>
		/// <param name="startIndex">Index within the list to begin</param>
		/// <param name="count">Total number of objects to load</param>
		/// <returns>Array list of additionRequest objects</returns>

		public ArrayList GetAdditionRequestList(int startIndex, int count)
		{
			try
			{
				ArrayList additionRequestList=null;
				additionRequestList=new ArrayList();
				DataTable dt=DataContainer.Tables[currentDataTableName]; 
				int rowCount=dt.Rows.Count;
				for (int i = startIndex, end = Math.Min(i + count,rowCount); i < end; ++i)
				{
					additionRequestList.Add(new ListAdditionRequest(CachePolicy,dt.Rows[i]));						
				}	
				return additionRequestList;
			}
			catch(Exception ex)
			{
				throw new Exception("Failed to get the addiition requests. Error occurred while executing the GetAdditionRequestList()", ex);
			}
		}

		/// <summary>
		/// Sort the list on a specified column.
		/// If the column to be sorted is the same as what was last sorted on, the sort sequence is toggled. 
		/// Else, the sort sequence is set to ascending.
		/// Note:This method uses datatable cloning and datarow import ,just to have the sorted list in the datacontainer with the same datatable name.This will help us to download the data in the sorted order
		/// </summary>
		/// <param name="columnName">Column to sort on</param>
		public void Sort(string columnName)
		{			
			sortAscending = (sortColumn == columnName) ? !sortAscending : AscendingSortSequence;
			sortColumn = columnName;

			DataTable dataTable = DataContainer.Tables[currentDataTableName];
			DataView dataView = dataTable.DefaultView;
			dataView.Sort = string.Format("{0} {1}", columnName, sortAscending ? SortSequenceAscending : SortSequenceDescending);

			DataTable sortedDataTable = dataTable.Clone();
			foreach (DataRowView rowView in dataView)
			{
				sortedDataTable.ImportRow(rowView.Row);
			}
			DataContainer.Tables.Remove(currentDataTableName);
			DataContainer.Tables.Add(sortedDataTable);
			DataContainer.Tables[0].TableName=currentDataTableName;
		}

		/// <summary>
		/// Returns a datatable of requests for use when downloading to an application
		/// such as Excel or pdf
		/// </summary>
		public DataTable GetApplicationsForDownload()
		{
			if ( null == DataContainer  ||  DataContainer.Tables.Count < 1 )
			{
				throw new Exception("Failed to get the addition requests for download. Error occurred while executing the GetApplicationsForDownload()");
			}
			return DataContainer.Tables[currentDataTableName];
		}
		#endregion

		
	}
}

